import { ref } from 'vue'
import { adapter, request } from '@/request'
import { packageDataByGet } from '@/core/api/priceSheet'
import type { RequestWrapper } from '@/core/interfaces/common'
import { useMainStore } from '@/store/useMainStore'
const mainStore = useMainStore()
interface RawPackageData {
  id: number
  comboName: string
  wordsNumTotal: number
  wordsNumEverTime: number
  productId?: number
  giftNumber?: number
}

export interface PackageData extends RawPackageData {
  label: string
  value: number
  originLabel: string
}
interface Params {
  productId: number
}

export default function getPackageList() {
  const service = adapter<RequestWrapper<RawPackageData[]>>(request)
  const loading = ref(false)
  const response = ref<PackageData[]>([])
  const fetch = (params: Params) => {
    const { url, method } = packageDataByGet()
    loading.value = true
    return service({
      config: {
        url,
        method,
        params
      },
      callback: (res) => {
        response.value = res.data.data.map((item) => {
          return {
            ...item,
            label: item.wordsNumTotal === 0 ? `${item.comboName}` : `${item.comboName}`,
            originLabel: item.comboName,
            value: item.id,
            productId: item.productId // 添加 productId字段
          }
        })

        // 添加安全检查，确保数组元素存在
        if (res.data.data[0]) {
          mainStore.zhibainhsds(res.data.data[0].giftNumber || 0)
          localStorage.setItem('giftNumberses1', JSON.stringify(res.data.data[0].giftNumber || 0))
        }
        if (res.data.data[1]) {
          mainStore.zhibainhsdsd(res.data.data[1].giftNumber || 0)
          localStorage.setItem('giftNumberses2', JSON.stringify(res.data.data[1].giftNumber || 0))
        }
        if (res.data.data[2]) {
          localStorage.setItem('giftNumberses123', JSON.stringify(res.data.data[2].giftNumber || 0))
        }
      },
      error: (err) => {
        localStorage.removeItem('giftNumber')
        console.log(err)
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [response, fetch, loading] as const
}
